

<template>
  <div class="detailed-gender-out">
    <el-select v-model="value" placeholder="选择年份" style="width: 200px ; position: absolute ;  top: 30px ;z-index: 100">
      <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
          :disabled="item.disabled"
      />
    </el-select>
    <div class="detailed-item" id="detailed-homeStruct-main">
    </div>
  </div>
</template>

<style scoped>

</style>

<script setup>

import {onMounted, ref, watch} from "vue";
import {getHomeStruct} from "@/api/homeStruct.js";
import {useDetailedStore} from "@/store/useDetailedStore.js";
import {detailedHomeStructEvent} from "@/consts/eventName.js";
import * as echarts from "echarts";
import emitter from "@/utils/emitter.js";
import theme from "../../../../static/theme/walden.json"


let value = ref("")
let options = []

let chartDom
let myChart
let option

let detailed = useDetailedStore()

let city

for (let i = 2002; i < 2024; i++) {
  options.push({
    value: i,
    label: i+'年',
  })
}

onMounted(()=>{
  detailed.detailedLoadFlag.set(detailedHomeStructEvent,true)
  let data = detailed.detailedData.get(detailedHomeStructEvent)

  chartDom = document.getElementById('detailed-homeStruct-main');
  myChart = echarts.init(chartDom,theme);

  city = data.city

  option = createOption(data.value,city)

  option && myChart.setOption(option);
})

emitter.on(detailedHomeStructEvent,(value)=>{
  city = value.city
  option = createOption(value.value,city)
  option && myChart.setOption(option);
})


watch(value,(newValue)=>{
  getHomeStruct(city,newValue).then((value)=>{
    let data = value.data
    if (data.code === 404){
      alert("没有该年数据")
    }
    let res = []
    console.log(data)

    data.forEach((item)=>{
      const jsonMap = new Map(Object.entries(item));
      res.push({
        name:jsonMap.keys().next().value,
        value:jsonMap.values().next().value
      })
    })

    return res

  }).then((value)=>{
    option = createOption(value,city)

    option && myChart.setOption(option);
  })
})


function createOption(data,city){
  if (city === "china"){
    city = "中国"
  }
  return {
    title: {
      y: 'top',
      x:'left',
      text: city+'-家庭结构',
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)'
    },
    legend:{
      show:true,
      orient: 'vertical',
      x:'right',      //可设定图例在左、右、居中
      y:'center',     //可设定图例在上、下、居中

    },
    series: [
      {
        name:"家庭结构",
        type: 'pie',
        radius: [50, 200],
        roseType: 'radius',
        itemStyle: {
          borderRadius: 5
        },
        label: {
          show:true
        },
        emphasis: {
          label: {
            show: true
          }
        },
        data: data,

      },

    ]
  };
}

</script>